package com.bjtang.fileSync.nio;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.SocketChannel;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 非阻塞的nio多线程处理 ，bjtang 2024.1.12
 */
public class NonBlockingHandler implements Runnable {
	private static Logger logger = LogManager.getLogger("miko-file");
	private FileService fileService;
	private SocketChannel socketChannel;
	private SocketDto socketDto;

	public NonBlockingHandler(SocketChannel socketChannel, SocketDto socketDto) {
		this.socketChannel = socketChannel;
		this.socketDto = socketDto;
	}

//	@Override
	public void run() {
		handle(socketChannel, socketDto);
	}

	public void handle(SocketChannel socketChannel, SocketDto socketDto) {
		logger.info("进入业务处理环节" + socketDto.getFileMethod());

		// TODO 存在问题,通过反射执行方法会导致new 新对象,导致一直在读配置文件
		try {
			if (fileService == null) {
				fileService = FileService.class.getConstructor().newInstance();
			}
			// 通过反射直接执行对应方法
			FileService.class.getMethod(socketDto.getFileMethod(), SocketChannel.class, SocketDto.class)
					.invoke(fileService, socketChannel, socketDto);
			socketChannel.close();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (socketChannel != null) {
					socketChannel.close();
				}
			} catch (IOException e) {
				logger.error(e);
			}
		}
	}
}
